/* eslint-disable */
import axios from 'axios'

// 配置axios基础URL
const API_BASE_URL = 'http://localhost:8081/api'

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
apiClient.interceptors.request.use(
  config => {
    console.log('发送请求:', config.method?.toUpperCase(), config.url)
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
apiClient.interceptors.response.use(
  response => {
    console.log('收到响应:', response.status, response.config.url)
    // 后端返回的数据格式: { success: boolean, message: string, data: any }
    if (response.data && response.data.success) {
      return response.data.data
    } else {
      throw new Error(response.data?.message || '请求失败')
    }
  },
  error => {
    console.error('响应错误:', error)
    if (error.response) {
      // 服务器返回错误状态码
      const message = error.response.data?.message || `请求失败: ${error.response.status}`
      throw new Error(message)
    } else if (error.request) {
      // 请求发送失败
      throw new Error('网络连接失败，请检查后端服务是否启动')
    } else {
      // 其他错误
      throw new Error(error.message || '未知错误')
    }
  }
)

// 文章API类
class ArticleAPI {
  // 获取所有文章
  async getAll(params = {}) {
    try {
      const {
        page = 1,
        size = 100,
        keyword,
        category,
        status,
        collection, // 新增：合集筛选参数
        sortBy = 'updatedAt',
        sortOrder = 'desc'
      } = params
      
      const queryParams = {
        page,
        size,
        sortBy,
        sortOrder
      }
      
      if (keyword) queryParams.keyword = keyword
      if (category) queryParams.category = category
      if (status) queryParams.status = status
      if (collection !== undefined) queryParams.collection = collection // 新增：传递合集参数
      
      const response = await apiClient.get('/articles', { params: queryParams })
      
      // 返回文章列表，兼容原有的数组格式，并将collectionId映射为collection
      const articles = response.content || []
      return articles.map(article => ({
        ...article,
        collection: article.collectionId || '', // 将后端的collectionId映射为前端的collection
        collectionId: undefined // 删除collectionId字段避免混淆
      }))
    } catch (error) {
      console.error('获取文章列表失败:', error)
      throw error
    }
  }
  
  // 根据ID获取文章
  async getById(id) {
    try {
      const article = await apiClient.get(`/articles/${id}`)
      // 将后端的collectionId映射为前端的collection
      return {
        ...article,
        collection: article.collectionId || '',
        collectionId: undefined
      }
    } catch (error) {
      console.error('获取文章失败:', error)
      throw error
    }
  }
  
  // 创建文章
  async create(articleData) {
    try {
      const now = new Date().toISOString()
      
      const newArticle = {
        title: articleData.title || '无标题',
        content: articleData.content || '',
        summary: this.generateSummary(articleData.content || ''),
        status: articleData.status || 'draft',
        category: articleData.category || '',
        collectionId: articleData.collection || '', // 修正：使用collectionId字段
        tags: articleData.tags || [],
        wordCount: this.countWords(articleData.content || ''),
        readTime: this.calculateReadTime(articleData.content || ''),
        images: this.extractImages(articleData.content || '')
      }
      
      const createdArticle = await apiClient.post('/articles', newArticle)
      // 将后端返回的collectionId映射为前端的collection
      return {
        ...createdArticle,
        collection: createdArticle.collectionId || '',
        collectionId: undefined
      }
    } catch (error) {
      console.error('创建文章失败:', error)
      throw error
    }
  }
  
  // 更新文章
  async update(id, updateData) {
    try {
      const updateArticle = {
        ...updateData,
        wordCount: this.countWords(updateData.content || ''),
        readTime: this.calculateReadTime(updateData.content || ''),
        images: this.extractImages(updateData.content || '')
      }
      
      if (updateData.content) {
        updateArticle.summary = this.generateSummary(updateData.content)
      }
      
      // 确保合集字段被正确处理
      if (updateData.hasOwnProperty('collection')) {
        updateArticle.collectionId = updateData.collection || '' // 修正：使用collectionId字段
        delete updateArticle.collection // 删除前端字段
      }
      
      const updatedArticle = await apiClient.put(`/articles/${id}`, updateArticle)
      // 将后端返回的collectionId映射为前端的collection
      return {
        ...updatedArticle,
        collection: updatedArticle.collectionId || '',
        collectionId: undefined
      }
    } catch (error) {
      console.error('更新文章失败:', error)
      throw error
    }
  }
  
  // 删除文章
  async delete(id) {
    try {
      await apiClient.delete(`/articles/${id}`)
      return true
    } catch (error) {
      console.error('删除文章失败:', error)
      throw error
    }
  }
  
  // 批量删除文章
  async batchDelete(ids) {
    try {
      const result = await apiClient.delete('/articles/batch', {
        data: { ids }
      })
      return result
    } catch (error) {
      console.error('批量删除文章失败:', error)
      throw error
    }
  }
  
  // 搜索文章
  async search(keyword, options = {}) {
    try {
      const {
        searchIn = 'all',
        caseSensitive = false,
        wholeWord = false,
        status,
        tags,
        startDate,
        endDate,
        page = 1,
        size = 100
      } = options
      
      const params = {
        keyword,
        searchIn,
        caseSensitive,
        wholeWord,
        page,
        size
      }
      
      if (status) params.status = status
      if (tags && tags.length > 0) params.tags = tags
      if (startDate) params.startDate = startDate
      if (endDate) params.endDate = endDate
      
      const result = await apiClient.get('/articles/search', { params })
      
      // 返回搜索结果，兼容原有格式
      return {
        articles: result.content || [],
        total: result.totalElements || 0,
        totalPages: result.totalPages || 0,
        currentPage: result.number + 1 || 1
      }
    } catch (error) {
      console.error('搜索文章失败:', error)
      throw error
    }
  }
  
  // 导出所有文章
  async exportAll() {
    try {
      const result = await apiClient.get('/articles/export')
      return result
    } catch (error) {
      console.error('导出文章失败:', error)
      throw error
    }
  }
  
  // 导入文章
  async importArticles(data, options = {}) {
    try {
      const { merge = false } = options
      
      const result = await apiClient.post('/articles/import', {
        articles: data,
        merge
      })
      
      return result
    } catch (error) {
      console.error('导入文章失败:', error)
      throw error
    }
  }
  
  // 清空所有文章
  async clear() {
    try {
      await apiClient.delete('/articles/clear')
      return true
    } catch (error) {
      console.error('清空文章失败:', error)
      throw error
    }
  }
  
  // 获取统计信息
  async getStatistics() {
    try {
      const statistics = await apiClient.get('/articles/statistics')
      return statistics
    } catch (error) {
      console.error('获取统计信息失败:', error)
      throw error
    }
  }
  
  // 获取所有分类
  async getAllCategories() {
    try {
      const categories = await apiClient.get('/articles/categories')
      return categories
    } catch (error) {
      console.error('获取分类失败:', error)
      throw error
    }
  }
  
  // 保存所有文章（兼容方法，实际不需要）
  async saveAll(articles) {
    console.warn('saveAll方法在后端API模式下不需要使用')
    return articles
  }
  
  // 生成文章摘要
  generateSummary(content, maxLength = 200) {
    if (!content) return ''
    
    // 移除Markdown语法
    const plainText = content
      .replace(/#{1,6}\s+/g, '') // 移除标题
      .replace(/\*\*(.*?)\*\*/g, '$1') // 移除粗体
      .replace(/\*(.*?)\*/g, '$1') // 移除斜体
      .replace(/`(.*?)`/g, '$1') // 移除行内代码
      .replace(/```[\s\S]*?```/g, '') // 移除代码块
      .replace(/!\[.*?\]\(.*?\)/g, '') // 移除图片
      .replace(/\[.*?\]\(.*?\)/g, '') // 移除链接
      .replace(/\n+/g, ' ') // 替换换行为空格
      .trim()
    
    return plainText.length > maxLength 
      ? plainText.substring(0, maxLength) + '...' 
      : plainText
  }
  
  // 统计字数
  countWords(content) {
    if (!content) return 0
    
    // 移除Markdown语法后统计字数
    const plainText = this.generateSummary(content, Infinity)
    
    // 中文字符按1个字计算，英文单词按空格分割计算
    const chineseChars = (plainText.match(/[\u4e00-\u9fa5]/g) || []).length
    const englishWords = plainText.replace(/[\u4e00-\u9fa5]/g, '').trim().split(/\s+/).filter(word => word.length > 0).length
    
    return chineseChars + englishWords
  }
  
  // 计算阅读时间
  calculateReadTime(content) {
    const wordCount = this.countWords(content)
    // 假设每分钟阅读200字
    return Math.ceil(wordCount / 200)
  }
  
  // 提取图片链接
  extractImages(content) {
    if (!content) return []
    
    const imageRegex = /!\[.*?\]\((.*?)\)/g
    const images = []
    let match
    
    while ((match = imageRegex.exec(content)) !== null) {
      images.push(match[1])
    }
    
    return images
  }
}

// 创建实例并导出
export const articleApi = new ArticleAPI()
export default articleApi